package ${domain}.config;

import net.sf.ehcache.CacheManager;
import net.sf.ehcache.config.CacheConfiguration;
import org.springframework.cache.Cache;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.ehcache.EhCacheCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import ${domain}.frame.auth.LocalData;

@Configuration
@EnableCaching
public class CacheConfig {

    public static final String TOKEN_CACHE = "tokenCache";

    /**
     * 获取缓存
     *
     * @param cacheName 缓存名称
     * @return
     */
    public static Cache getCache(String cacheName) {
        EhCacheCacheManager cacheManager = LocalData.getBean(EhCacheCacheManager.class);
        return cacheManager.getCache(cacheName);
    }

    @Bean
    public EhCacheCacheManager getCacheManager() {
        net.sf.ehcache.config.Configuration configuration = new net.sf.ehcache.config.Configuration();
        configuration.updateCheck(false);
        configuration.setUpdateCheck(false);
        CacheManager cacheManager = CacheManager.create(configuration);

        // 添加token缓存
        cacheManager.addCache(buildTokenCache());
        return new EhCacheCacheManager(cacheManager);
    }

    /**
     * 构建TokenCache
     *
     * @return 缓存
     */
    private net.sf.ehcache.Cache buildTokenCache() {
        CacheConfiguration config = new CacheConfiguration();
        config.setMemoryStoreEvictionPolicy("LFU");//最少使用
        config.setTimeToLiveSeconds(60 * 60);//最长有效时间
        config.setTimeToIdleSeconds(60 * 60);//无访问最长有效时间
        config.setName(TOKEN_CACHE);
        // 分配最大内存的10%作为token的缓存空间
        long memory = Runtime.getRuntime().maxMemory();
        config.setMaxBytesLocalHeap((long) (memory * 0.1f));
        return new net.sf.ehcache.Cache(config);
    }
}
